import java.io.IOException;
import java.net.*;
import java.util.Scanner;

public class UDPEchoClient {
    private DatagramSocket socket;
    //UDP本身不保存对端信息，需要在代码中保存
    private String serverIp ;
    private int serverPort;

    //在构造函数中指定访问的服务器地址
    public UDPEchoClient(String serverIp, int serverPort) throws SocketException {
        this.serverIp = serverIp;
        this.serverPort = serverPort;
        //这里必须使用无参的构造方法，由操作系统分配空闲端口
        socket = new DatagramSocket();
    }

    public void start() throws IOException {
        Scanner scan = new Scanner(System.in);

        while(true){
          //1.从控制台读取
          System.out.println("请输入要发送的内容：");
          String request = scan.next();

          //2.把请求发送给服务器
          //    构造过程不光要构造载荷，也要设置服务器IP和端口号
          //    IP是通过字符串来构造的，通过InetAddress.getByName(serverIp)把字符串转为Java标注库可识别的对象
          DatagramPacket requestPacket = new DatagramPacket(
                  request.getBytes(),
                  request.getBytes().length,
                  InetAddress.getByName(serverIp),
                  serverPort);


          //3.发送数据报
          socket.send(requestPacket);

          //4.接受服务器响应
          DatagramPacket responsePacket = new DatagramPacket(new byte[1024], 1024);
          socket.receive(responsePacket);


          //5.从服务器中读取数据进行解析并打印
          String response = new String(responsePacket.getData(), 0, responsePacket.getLength());
          System.out.println(response);
      }
    }

    static void main() throws IOException {
        UDPEchoClient client = new UDPEchoClient("127.0.0.1",9090);
        client.start();
    }
}
